// 员工管理独立模块，加载于 admin.js 之后
function emp$(sel){ return document.querySelector(sel); }
function empEscape(val){ if(val==null)return ''; return String(val).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }

let EMP_QUERY = { page: 1, pageSize: 10, name: '' };

document.addEventListener('DOMContentLoaded', () => {
  const btn = document.querySelector('nav button[data-view="employee"]');
  btn && btn.addEventListener('click', () => {
    loadEmployees(EMP_QUERY);
  });

  const searchForm = emp$('#employee-search-form');
  searchForm && searchForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    EMP_QUERY = Object.fromEntries(new FormData(searchForm).entries());
    EMP_QUERY.page = Number(EMP_QUERY.page || 1);
    EMP_QUERY.pageSize = Number(EMP_QUERY.pageSize || 10);
    await loadEmployees(EMP_QUERY);
  });

  const addBtn = emp$('#btn-employee-add');
  addBtn && addBtn.addEventListener('click', () => {
    emp$('#employee-modal-title').textContent = '新增员工';
    const form = emp$('#employee-form');
    form.reset();
    form.id.value = '';
    emp$('#employee-modal').classList.remove('hidden');
  });

  const cancelBtn = emp$('#employee-modal-cancel');
  cancelBtn && cancelBtn.addEventListener('click', () => {
    emp$('#employee-modal').classList.add('hidden');
  });

  const empForm = emp$('#employee-form');
  empForm && empForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const data = Object.fromEntries(new FormData(empForm).entries());
    const isEdit = !!data.id;
    const method = isEdit ? 'PUT' : 'POST';
    await API.send(method, '/admin/employee', {
      id: data.id || undefined,
      name: data.name,
      username: data.username,
      phone: data.phone,
      sex: data.sex,
      idNumber: data.idNumber,
    });
    emp$('#employee-modal').classList.add('hidden');
    await loadEmployees(EMP_QUERY);
  });

  const table = emp$('#employee-table');
  table && table.addEventListener('click', async (e) => {
    const btn = e.target.closest('button[data-action]');
    if (!btn) return;
    const id = btn.dataset.id;
    const action = btn.dataset.action;
    if (action === 'edit') {
      const res = await API.get(`/admin/employee/${id}`);
      const emp = res.data || res;
      emp$('#employee-modal-title').textContent = '编辑员工';
      const form = emp$('#employee-form');
      form.id.value = emp.id || id;
      form.name.value = emp.name || '';
      form.username.value = emp.username || '';
      form.phone.value = emp.phone || '';
      form.sex.value = emp.sex ?? '1';
      form.idNumber.value = emp.idNumber || '';
      emp$('#employee-modal').classList.remove('hidden');
    } else if (action === 'toggle') {
      const status = btn.dataset.nextStatus; // 0 或 1
      await API.send('POST', `/admin/employee/status/${status}?id=${id}`);
      await loadEmployees(EMP_QUERY);
    }
  });
});

async function loadEmployees(params) {
  const res = await API.get('/admin/employee/page', params);
  renderEmployeeTable('#employee-table', res, params);
}

function renderEmployeeTable(selector, res, params) {
  const el = document.querySelector(selector);
  if (!el) return;
  const data = res?.data || res || {};
  const records = data.records || [];
  const total = data.total || 0;
  const thead = `<thead><tr>
    <th>员工姓名</th><th>账号</th><th>手机号</th><th>账号状态</th><th>最后操作时间</th><th>操作</th>
  </tr></thead>`;
  const rows = records.map(r => {
    const statusText = r.status === 1 ? '启用' : '禁用';
    const statusDot = `<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${r.status===1?'#16a34a':'#ef4444'};margin-right:6px"></span>`;
    const nextStatus = r.status === 1 ? 0 : 1;
    return `<tr>
      <td>${empEscape(r.name)}</td>
      <td>${empEscape(r.username)}</td>
      <td>${empEscape(r.phone)}</td>
      <td>${statusDot}${statusText}</td>
      <td>${empEscape(r.updateTime || '')}</td>
      <td>
        <button data-action="edit" data-id="${r.id}" class="link">修改</button>
        <button data-action="toggle" data-id="${r.id}" data-next-status="${nextStatus}" class="link">${r.status===1?'停用':'启用'}</button>
      </td>
    </tr>`;
  }).join('');

  el.innerHTML = `
    <div class="total">共 ${total} 条</div>
    <div class="pagination">
      <button ${params.page<=1?'disabled':''} id="emp-prev">前往上一页</button>
      <span>第 ${params.page} 页</span>
      <button ${(params.page*params.pageSize)>=total?'disabled':''} id="emp-next">前往下一页</button>
    </div>
    <table>${thead}<tbody>${rows || ''}</tbody></table>
  `;

  el.querySelector('#emp-prev')?.addEventListener('click', async () => {
    if (EMP_QUERY.page > 1) {
      EMP_QUERY.page -= 1;
      await loadEmployees(EMP_QUERY);
    }
  });
  el.querySelector('#emp-next')?.addEventListener('click', async () => {
    if (EMP_QUERY.page * EMP_QUERY.pageSize < total) {
      EMP_QUERY.page += 1;
      await loadEmployees(EMP_QUERY);
    }
  });
}